<template>
<view class="container" :style="'height:' + (ProductshowWay==1? '100%':'')">
 <view class="typeSearchContainer"> 
    <view class="search_input_bg">
      <view class="user_logo" @tap="toUserPageFun()">
          <image class="user_logo_img" :src="loginUser.headimgurl?loginUser.headimgurl:'../../static/logo.png'" mode="aspectFill"></image>
      </view>
      <view class="search_input">
        <view class="search_input_left">
          <image class="input_img" src="https://image1.sansancloud.com/xianhua/2018_9/14/16/25/0_222.jpg?x-oss-process=style/preview_120"></image>
          <input class="input" @confirm="getSearchProductName" @input="searchProductValue" placeholder="搜索产品名"></input>
        </view>
        <view class="empty_button" @tap="getSearchProductName">x</view>
      </view>
      <view class="dianpu_list" @tap="bindProductshowWay">
          <block v-if="ProductshowWay == 2">
              <image class="dianpu_icon" mode="aspectFit" src="../../static/ditu.png"></image>
              <text>切回地图</text>
          </block>
          <block v-if="ProductshowWay == 1">
              <image class="dianpu_icon" mode="aspectFit" src="../../static/dianpu.png"></image>
              <text>附近店铺</text>
          </block>
      </view>
    </view>
  </view>
    <block v-if="ProductshowWay == 2">
     <view class="product_page_container2">
        <block v-if="productData.length!=0">
          <view class="product_data_list" :data-info="result" v-for="(result, index) in productData" :key="index">
            <view class="product_info_main">
              <view class="product_info">
                  <image class="product_info_left" :src="(result.shop_logo||'https://image1.sansancloud.com/xianhua/2021_3/15/17/56/9_413.jpg?x-oss-process=style/preview_120')"></cover-image>
                  <view class="product_info_center">
                    <view class="product_info_name">{{result.shop_name}}</view>
                    <view class="product_info_service_time">
                      <image class="product_info_service_time_img" src="../../static/juli.png"></image>
                      <view class="product_info_service_value">({{result.dis}}m)</view>
                    </view>
                    <view class="product_info_service_addr">
                      <image class="product_info_service_addr_img" src="../../static/dizhi.png"></image>
                      <view class="product_info_service_value" style="width:80%; word-break: break-all;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">{{result.contact_address}}</view>
                    </view>
                  </view>
                  <view class="product_info_right" @tap="navigationToMap(result)" :data-info="result">
                    <!-- <cover-view class="line"></cover-view> -->
                    <view class="navigation">导航</view>
                    <!-- <cover-image src="https://image1.sansancloud.com/xianhua/2018_9/13/20/11/36_801.jpg?x-oss-process=style/preview_120" class="navigation"></cover-image> -->
                  </view>
              </view>
              <view class="chongdianbao_num_block">
                  <view class="chongdianbao_num_block_item">
                      <image class="chongdianbao_num_block_item_img" src="../../static/kejie.png"></image>
                      <view class="chongdianbao_num">可借：0</view>
                  </view>
                  <view class="chongdianbao_num_block_item">
                      <image class="chongdianbao_num_block_item_img" src="../../static/kehuan.png"></image>
                      <view class="chongdianbao_num">可还：0</view>
                  </view>
              </view>
            </view>
          </view>
        </block>
        <block v-else>
          <view class="noproduct">
            <image mode="widthFix" src="https://image1.sansancloud.com/xianhua/2019_12/16/15/54/55_950.jpg?x-oss-process=style/preview_120"></image>
            <text>没有相关商品</text>
          </view>
        </block>
      </view>
    </block>


    <block v-if="ProductshowWay == 1">
     <view class="product_page_container2" style="position:fixed;height:100%">
          <map class="mapItem" id="map" :circles="circles" :longitude="localPoint.longitude" :latitude="localPoint.latitude" scale="14" @controltap="controltap" :markers="markers" @markertap="markertap" @regionchange="regionchange" show-location="true" style="width: 100%; height: 100%;" @tap="hiddenProInfo">
            <cover-view class="play">
               <cover-image class="img" src="https://image1.sansancloud.com/xianhua/2020_1/19/19/33/5_703.jpg?x-oss-process=style/preview_120" style="width:80rpx;height:80rpx;"></cover-image>
            </cover-view>
          </map>
          <cover-view class="bottom_tap">
            <cover-view class="location">
              <cover-image src="../../static/dingwei.png" class="location_img" @tap="clickcontrol"></cover-image>
            </cover-view>
            <cover-view class="return_index">
              <cover-image src="../../static/fuwu.png" class="return_index_img" @tap="calling('4009661039')"></cover-image>
            </cover-view>
          </cover-view>
          <cover-view class="scan_code" v-if="productDetail==null&&ProductshowWay==1" @tap="scanCodeFun()" style="background-image:linear-gradient(to right,#80dcd9,#5dbbba)">
              <cover-image class="scan_code_img" src="../../static/saoma.png"></cover-image>
              <cover-view style="background: #59bfba00;">扫码充电</cover-view>
          </cover-view>
          <cover-view class="product_data" v-if="productDetail!=null&&ProductshowWay==1">
            <cover-view class="product_info_main">
              <cover-view class="product_info">
                  <cover-image class="product_info_left" :src="(productDetail.shop_logo||'https://image1.sansancloud.com/xianhua/2021_3/15/17/56/9_413.jpg?x-oss-process=style/preview_120')"></cover-image>
                  <cover-view class="product_info_center">
                    <cover-view class="product_info_name">{{productDetail.shop_name}}</cover-view>
                    <cover-view class="product_info_service_time">
                      <cover-image class="product_info_service_time_img" src="../../static/juli.png"></cover-image>
                      <cover-view class="product_info_service_value">({{productDetail.dis}}m)</cover-view>
                    </cover-view>
                    <cover-view class="product_info_service_addr">
                      <cover-image class="product_info_service_addr_img" src="../../static/dizhi.png"></cover-image>
                      <cover-view class="product_info_service_value" style="width:96%; word-break: break-all;text-overflow: ellipsis;white-space: nowrap;">{{productDetail.contact_address}}</cover-view>
                    </cover-view>
                  </cover-view>
                  <cover-view class="product_info_right" @tap="navigationToMap(productDetail)" :data-info="productDetail">
                    <!-- <cover-view class="line"></cover-view> -->
                    <cover-view class="navigation">导航</cover-view>
                    <!-- <cover-image src="https://image1.sansancloud.com/xianhua/2018_9/13/20/11/36_801.jpg?x-oss-process=style/preview_120" class="navigation"></cover-image> -->
                  </cover-view>
              </cover-view>
              <cover-view class="chongdianbao_num_block">
                  <cover-view class="chongdianbao_num_block_item">
                      <cover-image class="chongdianbao_num_block_item_img" src="../../static/kejie.png"></cover-image>
                      <cover-view class="chongdianbao_num">可借：{{productDetail.kejie}}</cover-view>
                  </cover-view>
                  <cover-view class="chongdianbao_num_block_item">
                      <cover-image class="chongdianbao_num_block_item_img" src="../../static/kehuan.png"></cover-image>
                      <cover-view class="chongdianbao_num">可还：{{productDetail.kehuan}}</cover-view>
                  </cover-view>
              </cover-view>
            </cover-view>
          </cover-view>
      </view>
      </block>
      <!-- 授权窗口 -->
      <view v-if="showPopup">
        <view class='authorizationBg'></view>
        <view class='authorization'>
          <view class='authorizationPopup'>
            <view class='tipContent'>
              <text style="font-size:38rpx;">前往微信授权</text>
            </view>
            <view class='buttonArray'>
              <button class='button cancel' bindtap='cancel'>取消</button>
              <button v-if="programType=='weixin'" class='button confirm' open-type="getUserInfo" @getuserinfo="bindGetUserInfo">确定</button>
              <button v-else class='button confirm' open-type="getAuthorize" scope="userInfo" @getAuthorize="bindGetUserInfo">确定</button>
            </view>
          </view>
        </view>
      </view>
</view>
</template>

<script>

export default {
  data() {
    return {
      setting: null,
      // setting   
      showPopup:false,
      productData: [],
      programType:getApp().globalData.programType,
      circles:[{
            latitude: '26.080429',
            longitude: '119.30347',
            color: '#869fe1DD',
            fillColor: '#e3e6ed88',
            radius: 4000,
            strokeWidth: 2
          }],
      sysWidth: 320,
      //图片大小
      positionTab: '',
      ProductshowWay: 1,
      // ProductshowWay列表显示方法 (默认显示地图)
      localPoint: {
        longitude: '0',
        latitude: '0'
      },
      productDetail: null,
      markers: [
      ],

      /* 全部参数 */
      params: {
        page: 1,
        latitude: '0',
        longitude: '0',
        size:20,
        distance:500
      },
      listPage: {
        page: 1,
        pageSize: 20,
        totalSize: 0,
        curpage: 1,
      },
      currentItem: "",
      showType: false,
      bindProductTypeIndex: "",
      focusTypeItem: "",
      EARTH_RADIUS : 6378.137,
      loginUser:getApp().globalData.loginUser,
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.getCrlcle()
    uni.getLocation({
      // type: 'gcj02',
      //返回可以用于uni.openLocation的经纬度
      success: function (res) {
        console.log(res);
        that.localPoint.latitude = res.latitude;
        that.localPoint.longitude = res.longitude;
        that.params.latitude = res.latitude;
        that.params.longitude = res.longitude;
        let circles=that.circles;
        circles[0].longitude=res.longitude
        circles[0].latitude=res.latitude
        that.setData({
            circles:circles
        });
        console.log("options", options);
        if (!!options.forceSearch && options.forceSearch == 2) {
          that.setData({
            ProductshowWay: 2
          });
        } else {
          that.setData({
            ProductshowWay: 1
          });
        }
        for (let i in options) {
          for (let j in that.params) {
            if (i.toLowerCase() == j.toLowerCase()) {
              that.params[j] = options[i];
            }
          }
        }
        that.setData({
          params: that.params,
          localPoint: that.localPoint
        });
        console.log(that.params);
        that.getData(that.params, 2);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.listPage.page = 1;
    this.params.page = 1;
    this.getData(this.params, 2);
    uni.showNavigationBarLoading();
    uni.hideNavigationBarLoading(); //完成停止加载

    uni.stopPullDownRefresh(); //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    console.log("====onReachBottom====",)
    if (that.listPage.totalSize* that.listPage.pageSize > that.listPage.curPage * that.listPage.pageSize) {
        console.log("======",that.listPage.totalSize* that.listPage.pageSize , that.listPage.curPage * that.listPage.pageSize)
      that.listPage.page++;
      that.params.page++;
      that.getData(that.params);
    }else{
        console.log("没有啦")
    }
  },
  methods: {
    calling: function (phoneNumber) {
      console.log('==phoneNumber===',phoneNumber)
      uni.makePhoneCall({
        phoneNumber: phoneNumber,
        success: function () {
          console.log("拨打电话成功！")
        },
        fail: function () {
          console.log("拨打电话失败！")
        }
      })
    },
    toUserPageFun:function(){
        uni.navigateTo({
          url: '/pages/user/index'
        });
    },
    toIndex() {
      getApp().globalData.toIndex();
    },

    clickcontrol(e) {
      //回到定位的
      let mpCtx = uni.createMapContext("map");
      mpCtx.moveToLocation();
    },
    rad:function (d) {
      return d * Math.PI / 180.0;
    },
    getDistance:function (lng1, lat1, lng2, lat2) {
      let that=this;
      var radLat1 = that.rad(lat1);
      var radLat2 = that.rad(lat2);
      var a = radLat1 - radLat2;
      var b = that.rad(lng1) - that.rad(lng2);
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
        + Math.cos(radLat1) * Math.cos(radLat2)
        * Math.pow(Math.sin(b / 2), 2)));
      s = s * that.EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      return s;//返回数值单位：公里
    },
    getCrlcle(){
        let that=this;
        var mapCtx = uni.createMapContext('map')
        mapCtx.getRegion({
          success: res => {
            console.log("====getRegion===",res);
            let lng1 = res.northeast?res.northeast.longitude:'';
            let lat1 = res.northeast?res.northeast.latitude:'';
            let lng2 = res.northeast?res.southwest.longitude:'';
            let lat2 = res.northeast?res.southwest.latitude:'';
    
            let longitude = lng1 - lng2;
            let latitude = lat1 - lat2;
            let flag = longitude > latitude ? true : false;
            let radius = 0;
            //计算得到短边，然后再通过*1000转变为m，除2得到半径，*0.8优化显示，让圈圈只占界面的80%
            if (flag) {
              radius = that.getDistance(lng1, lat1, lng1, lat2) * 1000 / 2 * 0.8;
            } else {
              radius = that.getDistance(lng1, lat1, lng2, lat1) * 1000 / 2 * 0.8;
            }
            console.log("===radius===",radius)
            let circles=that.circles;
            circles[0].radius=radius
            that.setData({
                circles:circles
            });
          }
        });
    },
    getCenterPoint(callback) {
      let that = this;
      var mapCtx = uni.createMapContext('map');
      mapCtx.getCenterLocation({
        success: function (res) {
          console.log('res', res);
          that.params.latitude = res.latitude;
          that.params.longitude = res.longitude;
          let circles=that.circles;
          circles[0].longitude=res.longitude
          circles[0].latitude=res.latitude
          that.setData({
            params: that.params,
            circles:circles
          });

          if (callback) {
            callback(that.params, 2);
          }
        }
      }); //获取当前地图的中心经纬度
    },
    regionchange(e) {
      console.log('===regionchange===', e);

      if (e.type == 'end') {
        if (e.causedBy == 'scale') {
          console.log('====scale====');
        } else if (e.causedBy == 'drag') {
          console.log('====drag====');
          this.getCenterPoint(this.getData);
        } else {
          console.log('====all====');
          this.getCenterPoint(this.getData);
        }
      }
    },

    markertap(e) {
      console.log(e);
      this.toProductDetailMap(e.detail.markerId);
    },
    controltap(e) {
      console.log(e);
    },
    hiddenProInfo(e) {
      console.log(e);
      this.setData({
        productDetail: null
      });
    },
    bindGetUserInfo: function (e) {
      let that = this;
      console.log("===bindGetUserInfo===",e)
      that.showPopup=false
      console.log("getApp().globalData.loginUser",getApp().globalData.loginUser,getApp().globalData.openid)
      console.log(e.detail.userInfo)
      if(that.programType=='weixin'){
          if (e.detail.userInfo) {
            //用户按了允许授权按钮
            console.log('用户按了允许授权按钮');
            let param={nickname:e.detail.userInfo.nickName,headimgurl:e.detail.userInfo.avatarUrl};
            console.log("getApp().globalData.loginUser",getApp().globalData.loginUser)
            that.$set(getApp().globalData.loginUser,'nickname',e.detail.userInfo.nickName)
            that.$set(getApp().globalData.loginUser,'headimgurl',e.detail.userInfo.avatarUrl)
            that.loginUser=getApp().globalData.loginUser
            getApp().globalData.setloginUser(getApp().globalData.loginUser)
            that.bindUserData(param)
          } else {
            console.log('用户按了拒绝按钮')
            //用户按了拒绝按钮
          }
      }else{
          that.loginUser=getApp().globalData.loginUser
          let param={nickname:'',headimgurl:''};
          that.bindUserData(param)
      }
    },
    cancel: function () {
      this.showPopup=false;
    },
    bindUserData: function (param) {
      let params=Object.assign({},param,{openid:getApp().globalData.openid})
      var customIndex = getApp().globalData.AddClientUrl("/user/bindGet", params);
      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      uni.request({
        url: customIndex.url,
        param:customIndex.params,
        header: that.header,
        method: 'POST',
        success: function (res) {
          uni.hideLoading();
          console.log(res.data);
          uni.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          uni.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    //扫一扫 核销
    scanCodeFun: function (e) {
      let that = this;
      getApp().globalData.checkWxAuthUserInfo(function(){
          uni.scanCode({
            onlyFromCamera: true,
            scanType: ['qrCode'],
            success: scanRes => {
              console.log("scanCodeFun", scanRes, scanRes.result);
              let parameters=scanRes.result.split('?');
              console.log("==parameters==",parameters);
              let url='/pages/scan_sure_page/index?'+parameters[1]
              uni.navigateTo({
                url: url
              });
            }
          });
      },function(){
          that.programType=getApp().globalData.programType;
          that.showPopup=true
      });
    },
    navigationToMap:function(info){
        console.log("===navigationToMap==",info)
        getApp().globalData.navigationToMap(info)
    },
    /* 获取数据 */
    getData: function (param, ifAdd) {
      if (!ifAdd) {
        ifAdd = 1;
      }
      var customIndex = getApp().globalData.AddClientUrl("/shop/nearby", param);
      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      uni.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          uni.hideLoading();
          console.log("===nearby===",res.data);
          that.listPage.curPage = param.page;
          that.listPage.totalSize = res.data.data[0].totalPage;
          let dataArr = that.productData;
          let tagArray = [];

          if (ifAdd == 2) {
            dataArr = [];
          }

          if (!res.data.data || res.data.data.length == 0) {
            that.setData({
              productData: null
            });
          } else {
            if (dataArr == null) {
              dataArr = [];
            }
            dataArr = dataArr.concat(res.data.data);
            that.setData({
              productData: dataArr
            });
          }

          that.setData({
            markers: that.productData
          });
          let conut = 0;

          if (that.markers) {
            for (let i = 0; i < that.markers.length; i++) {
              if (that.markers[i].categoryIcon) {
                that.downProIcon(that.markers[i].categoryIcon, function (url) {
                  conut++;
                  that.markers[i].iconPath = url;
                  that.markers[i].width = 20;
                  that.markers[i].height = 25;

                  if (conut == that.markers.length) {
                    that.setData({
                      markers: that.markers
                    });
                    console.log('==that.data.markersHave===', that.markers);
                  }
                });
              } else {
                conut++;
                that.markers[i].iconPath = '/static/mapItem.png';
                that.markers[i].width = 20;
                that.markers[i].height = 25;

                if (conut == that.markers.length) {
                  that.setData({
                    markers: that.markers
                  });
                  console.log('==that.data.markers===', that.markers);
                }
              }
            }
          }

          uni.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          uni.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    downProIcon: function (url, callback) {
      var _this = this;

      if (getApp().globalData.mapProIconArray[encodeURIComponent(url)]) {
        console.log('已存在', encodeURIComponent(url));
        callback(getApp().globalData.mapProIconArray[encodeURIComponent(url)]);
        return;
      }

      uni.downloadFile({
        url: url.replace('http', 'https'),
        success: function (res) {
          console.log('下载图片', res);

          if (res.statusCode == 200) {
            callback(res.tempFilePath);
            getApp().globalData.mapProIconArray[encodeURIComponent(url)] = res.tempFilePath;
          }
        }
      });
    },
    /* 查找商品 */
    getSearchProductName: function (e) {
      console.log(e);

      if (e.detail.value) {
        this.params.productName = e.detail.value;
      } else {
        this.params.productName = '';
      }

      var that = this;
      var customIndex = this.more_product_list_URLFun(this.params);
      console.log(customIndex);
      getApp().globalData.showToastLoading('loading', true);
      uni.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          uni.hideLoading();

          if (!res.data.result || res.data.result.length == 0) {
            that.setData({
              productData: null
            });
          } else {
            that.setData({
              productData: res.data.result
            });
          }

          that.setData({
            markers: that.productData
          });
          let conut = 0;
          console.log("===markers===",that.markers)
          if (that.markers) {
            for (let i = 0; i < that.markers.length; i++) {
              if (that.markers[i].categoryIcon) {
                that.downProIcon(that.markers[i].categoryIcon, function (url) {
                  conut++;
                  that.markers[i].iconPath = url;
                  that.markers[i].width = 32;
                  that.markers[i].height = 32;

                  if (conut == that.markers.length) {
                    that.setData({
                      markers: that.markers
                    });
                    console.log('==that.data.markersHave===', that.markers);
                  }
                });
              } else {
                conut++;
                that.markers[i].iconPath = '/wxcomponents/images/icons/mapItem.png';
                that.markers[i].width = 32;
                that.markers[i].height = 32;

                if (conut == that.markers.length) {
                  that.setData({
                    markers: that.markers
                  });
                  console.log('==that.data.markers===', that.markers);
                }
              }
            }
          }
        },
        fail: function () {
          uni.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    more_product_list_URLFun: function (params) {
      let resule = getApp().globalData.AddClientUrl("/more_product_list.html", params);
      return resule;
    },

    /* 商品显示方法 */
    bindProductshowWay: function () {
      if (this.ProductshowWay == 1) {
        this.setData({
          ProductshowWay: 2
        });
      } else {
        this.setData({
          ProductshowWay: 1
        });
      }
    },
    toProductDetailMap: function (id) {
      console.log("--------toProductDetailMap------",id);
      var that = this;
      var param = {
        productId: id
      };
      for(let i=0;i<that.productData.length;i++){
          if(that.productData[i].id==id){
              that.productDetail=that.productData[i]
          }
      }
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>